package com.acwing.partition9;

import java.io.*;

/**
 * @author `RKC`
 * @date 2021/11/25 16:35
 */
public class AC875快速幂 {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(reader.readLine().split(" ")[0]);
        while (n-- > 0) {
            String[] s = reader.readLine().split(" ");
            int a = Integer.parseInt(s[0]), k = Integer.parseInt(s[1]), p = Integer.parseInt(s[2]);
            writer.write(quickPow(a, k, p) + "\n");
            writer.flush();
        }
    }

    private static long quickPow(int a, int k, int p) {
        long res = 1;
        while (k != 0) {
            if ((k & 1) == 1) res = res * a % p;
            k >>= 1;
            a = a * a % p;
        }
        return res;
    }
}
